<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: lilongfei
 * Date: 2016/12/11
 * Time: 下午1:33
 */

class Curl {


    private  $host;

    private $token;

    private $curl;

    /**
     * Curl constructor.
     */
    public function __construct($config = array())
    {
        $this->host = $config['host'];
        $this->token = isset($config['token']);
        $this->curl = curl_init();
        curl_setopt($this->curl, CURLOPT_HEADER, false);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        return $this;
    }

    public function get($url,$type = "json"){
        curl_setopt($this->curl, CURLOPT_URL, $this->host."/".$url);
        $response = curl_exec($this->curl);
        curl_close($this->curl);
        if($type == "json"){
            return json_decode($response,true);
        }
        return null;
    }
    public function post($url,$params,$type="json"){
        curl_setopt($this->curl, CURLOPT_URL, $this->host."/".$url);
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl,CURLOPT_POSTFIELDS,$params);
        $result = curl_exec($this->curl);
        curl_close($this->curl);
        if($type == "json"){
            return json_decode($result,true);
        }
        return null;
    }
    public function put($url,$params,$type="json"){
        curl_setopt($this->curl, CURLOPT_URL, $this->host."/".$url);
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "post");
        curl_setopt($this->curl,CURLOPT_HTTPHEADER,array("X-HTTP-Method-Override: PUT"));
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl,CURLOPT_POSTFIELDS,$params);
        $result = curl_exec($this->curl);
        curl_close($this->curl);
        if($type == "json"){
            return json_decode($result,true);
        }
        return null;
    }
    public function delete($url,$params,$type="json"){
        curl_setopt($this->curl, CURLOPT_URL, $this->host."/".$url);
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "post");
        curl_setopt($this->curl,CURLOPT_HTTPHEADER,array("X-HTTP-Method-Override: DELETE"));
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl,CURLOPT_POSTFIELDS,$params);
        $result = curl_exec($this->curl);
        curl_close($this->curl);
        if($type == "json"){
            return json_decode($result,true);
        }
        return null;
    }
}